package hu.plusone.fakecommander.util.picture;

import hu.plusone.fakecommander.util.Coupler;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import org.springframework.util.Assert;

public class ByteArrayCoupler implements Coupler<byte[]> {

    public static final int MB = 1024 * 1024;
    private static final Random RANDOM = new Random(System.currentTimeMillis());

    private final int fileSizeMax;
    private final int fileSizeMin;

    public ByteArrayCoupler(int fileSizeMinInByte, int fileSizeMaxInByte) {
        Assert.isTrue(fileSizeMinInByte < fileSizeMaxInByte);
        fileSizeMax = fileSizeMaxInByte;
        fileSizeMin = fileSizeMinInByte;
    }

    public List<byte[]> couple(final byte[] data) {
        Assert.notNull(data);

        List<byte[]> files = new ArrayList<byte[]>();

        if (data.length < fileSizeMax) {
            files.add(data);
            return files;
        }

        int offset = 0;
        while (offset < data.length) {
            int endOfFile = Math.min(offset + getRandomFileSize(), data.length);
            byte[] file = Arrays.copyOfRange(data, offset, endOfFile);
            files.add(file);
            offset = endOfFile;
        }

        return files;
    }

    public byte[] decouple(List<byte[]> dataList) {
        int size = sizeOfDataList(dataList);

        byte[] bs = new byte[size];
        int idx = 0;
        for (byte[] data : dataList) {
            for (byte b : data) {
                bs[idx] = b;
                idx++;
            }
        }
        return bs;
    }

    private int getRandomFileSize() {
        return fileSizeMin + RANDOM.nextInt(fileSizeMax - fileSizeMin);
    }

    private int sizeOfDataList(List<byte[]> dataList) {
        int size = 0;
        for (byte[] data : dataList) {
            for (byte b : data) {
                size++;
            }
        }
        return size;
    }

}
